package com.kaiwukj.android.ufamily.mvp.ui.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.MyApplication;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayInfo;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.AlipayResult;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.CustomPopupWindow;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.ShopWebView;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 果蔬商超
 */
@Route(path = ARouterUrlKt.ShopWebViewUrl)
public class ShopWebActivity extends BaseActivity {

    private static final int PAY_OK = 1;
    private static final int PAY_FAILED = 3;
    private static final int PAY_CANCEL = 2;

    public static final int ROUTER_WAY_SHOP = 1;
    public static final int ROUTER_WAY_ORDER = 2;
    public static final int ROUTER_WAY_DETAIL = 3;
    public static final int ROUTER_WAY_SEARCH = 4;
    public static final int ROUTER_WAY_CART = 5;

    @BindView(R.id.web)
    ShopWebView mWebView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    //@BindView(R.id.progress_bar)
    //ProgressBar progressBar;

    @Autowired
    int way;
    @Autowired
    int categoryId;
    @Autowired(name = "id")
    int goodsId;

    @OnClick(R.id.container_left)
    void back() {
        onBackPressedSupport();
    }

    private CustomPopupWindow popupWindow;

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_web_shop;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {


        String url;

        int communityId = MyApplication.getInstance().getSysCommunityId();
        String token = getApp().getToken();

        //int cacheStoreId = SPUtils.getInstance("app").getInt("storeId", 0);

        int storeId = MyApplication.getInstance().getStoreId();
        if (Constant.isLocalTest) {
            communityId = 0;
            storeId = 100;
        }

        switch (way) {
            case ROUTER_WAY_SHOP:
                url = String.format("%1$s#/?token=%2$s&storeId=%3$s&communityid=%4$s&categoryId=%5$s",
                        Constant.getShopUrl(), token, storeId, communityId, categoryId);
                break;
            case ROUTER_WAY_ORDER:
                url = String.format("%1$s#/order?token=%2$s", Constant.getShopUrl(), token);
                break;
            case ROUTER_WAY_DETAIL:
                url = String.format("%1$s#/details?token=%2$s&storeId=%3$s&communityid=%4$s&id=%5$s&source=%6$s",
                        Constant.getShopUrl(), token, storeId, communityId, goodsId, 5);
                break;
            case ROUTER_WAY_SEARCH:
                url = String.format("%1$s#/search?token=%2$s&storeId=%3$s&communityid=%4$s",
                        Constant.getShopUrl(), token, storeId, communityId);
                break;
            case ROUTER_WAY_CART:
                url = String.format("%1$s#/cart?token=%2$s&storeId=%3$s&communityid=%4$s&source=%5$s",
                        Constant.getShopUrl(), token, storeId, communityId, 1);
                break;
            default:
                url = "";
                break;
        }
        /*String url =
                String.format("http://172.168.1.66:8080/#/?token=%1$s&storeId=%2$s&communityid=%3$s",
                        token, storeId, communityId);*/

        LogUtils.d("url-------------->" + url);
        mWebView.loadUrl(url);
        //  mWebView.loadUrl("file:///android_asset/index1.html");

        mWebView.addOnPageStateListener(new ShopWebView.onPageStateListener() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                showLoading("正在加载...");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                hideLoading();
            }
        });

        /*mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (100 == newProgress) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);

            }
        });*/
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mWebView.setOnShopListener(new ShopWebView.OnShopListener() {
            @Override
            public void onTokenInvalid() {

            }

            @Override
            public void onPayByAli(String json) {
                runOnUiThread(() -> payByAli(json));
            }

            @Override
            public void onPayByWechat(String json) {
                payByWeChat(json);
            }

            @Override
            public void onGetPageTitle(String json) {
                if (!StringUtils.isEmpty(json)) {
                    runOnUiThread(() -> {
                        if (!isFinishing() && !isDestroyed()) {
                            tvTitle.setText(json);
                        }
                    });
                }
            }

            @Override
            public void onCallPhone(String json) {
                if (!StringUtils.isEmpty(json)) {
                    runOnUiThread(() -> callPhone(json));
                }
            }

            @Override
            public void onGoHome() {
                runOnUiThread(() -> goHome());
            }
        });
    }

    private void callPhone(String phone) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (popupWindow == null) {
            popupWindow = PopupWindowUtil.createCallDialog(this, phone);
        }
        popupWindow.showCenter(R.layout.activity_web_shop);
    }

    private void payByAli(String params) {
        AlipayResult payObj = GsonUtils.fromJson(params, AlipayResult.class);
        subscribe(Observable.create((ObservableOnSubscribe<PayResult>) emitter -> {
            PayTask payTask = new PayTask(this);
            Map<String, String> map = payTask.payV2(payObj.getSign(), true);
            emitter.onNext(new PayResult(map));
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(payResult -> {
                    if ("9000".equals(payResult.getResultStatus())) {
                        //EventBus.getDefault().post(new PayEvent(true, 0, "支付成功"));
                        mWebView.onPayResult(PAY_OK);
                    } else if ("6001".equals(payResult.getResultStatus())) {
                        //cancelOrder(new PayFeeCancelRequest(result.getTradeNo()));
                        mWebView.onPayResult(PAY_CANCEL);
                    } else {
                        //EventBus.getDefault().post(new PayEvent(false, 0, "支付失败"));
                        mWebView.onPayResult(PAY_FAILED);
                    }
                }));
    }

    private void payByWeChat(String params) {
        PayInfo payInfo = GsonUtils.fromJson(params, PayInfo.class);
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constant.WX_APP_ID);
        if (!msgApi.isWXAppInstalled()) {
            showMessage(getString(R.string.please_install_wechat));
            return;
        }
        msgApi.sendReq(payInfo.getPayReq());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent payEvent) {

        if (payEvent.isSuccess()) {
            //showMessage("支付成功哈");
            mWebView.onPayResult(PAY_OK);
        } else if (payEvent.getDesc().equals("支付已取消")) {
            mWebView.onPayResult(PAY_CANCEL);
        } else {
            mWebView.onPayResult(PAY_FAILED);
            showMessage(payEvent.getDesc());
        }
    }

    @Override
    public void onBackPressedSupport() {
        /*if (mWebView.allowGoBack()) {
            return;
        }*/
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressedSupport();
        }
    }

    public void goHome() {
        finish();
    }
}
